<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model.trim="listQuery.keyword"
        clearable
        :maxlength="33"
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入账号\姓名"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >查找</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >添加</el-button
      >
      <!-- <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
        >导出</el-button
      > -->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" width="100px" label="序号" type="index" />
      <el-table-column align="center" label="ID" prop="accountId" sortable />

      <el-table-column align="center" label="账号" prop="username" />

      <el-table-column align="center" label="姓名" prop="accountName" />

      <!-- <el-table-column align="center" label="头像" prop="avatar">
        <template slot-scope="scope">
          <img v-if="scope.row.avatar" :src="scope.row.avatar" width="40" />
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="角色" prop="roles">
        <template slot-scope="scope" v-if="scope.row && scope.row.roles">
          <el-tag
            v-for="item in scope.row.roles"
            :key="item.id"
            type="primary"
            style="margin-right: 4px;"
          >
            {{ item.name }}
          </el-tag>
        </template>
        <template v-else> </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            :disabled="scope.row && scope.row.accountId == 1"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            size="mini"
            :disabled="scope.row && scope.row.accountId == 1"
            @click="handleUpdate(scope.row, 2)"
            >绑定角色</el-button
          >
          <el-button
            type="danger"
            size="mini"
            :disabled="scope.row && scope.row.accountId == 1"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="changePagination"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="right"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input
            :disabled="dialogStatus == 'accredit'"
            :maxlength="33"
            placeholder="请输入姓名"
            v-model.trim="dataForm.name"
          />
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input
            :disabled="dialogStatus !== 'create'"
            placeholder="请输入账号"
            :maxlength="33"
            v-model.trim="dataForm.username"
          />
        </el-form-item>
        <el-form-item
          v-if="dialogStatus == 'create'"
          :maxlength="20"
          label="密码："
          prop="password"
        >
          <el-input
            v-model.trim="dataForm.password"
            type="password"
            placeholder="请输入密码"
            auto-complete="off"
          />
        </el-form-item>
        <el-form-item
          v-if="dialogStatus == 'create'"
          label="确认密码："
          prop="newPassword2"
        >
          <el-input
            :maxlength="20"
            v-model="dataForm.newPassword2"
            placeholder="请输入确认密码"
            type="password"
            auto-complete="off"
          />
        </el-form-item>
        <!-- <el-form-item label="头像" prop="avatar">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadAvatar"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="dataForm.avatar" :src="dataForm.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item> -->
        <el-form-item v-if="dialogStatus == 'accredit'" label="角色：">
          <el-select
            v-model="dataForm.selectRoles"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          :loading="loading"
          @click="createData"
          >确定</el-button
        >
        <el-button v-else type="primary" :loading="loading" @click="updateData"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {
  listAdmin,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  relation,
  bindRole
} from '@/api/admin'
import { roleOptions } from '@/api/role'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import md5 from 'md5'
export default {
  name: 'Admin',
  components: { Pagination },
  data () {
    var validateUserName = (rule, value, callback) => {
      var reg = /^[0-9A-Za-z/]{1,16}$/ //8-16位且同时包含数字和字母
      if (value === '') {
        callback(new Error('请输入账号'))
      } else if (!reg.test(value)) {
        callback(new Error('账号由16位以内的数字、大小写字母组成!'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#$%^&*()_+`\-={}:";'<>?,./]{8,16}$/ //8-16位且同时包含数字和字母
      console.log('reg.test(value)', value, !reg.test(value))
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!reg.test(value)) {
        callback(new Error('密码由8-16位且同时包含数字和字母组成!'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      uploadPath,
      list: null,
      total: 0,
      roleOptions: null,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        keyword: undefined,
        // sort: 'add_time',
        // order: 'desc'
      },
      dataForm: {
        id: undefined,
        username: undefined,
        password: undefined,
        newPassword2: undefined,
        name: undefined,
        avatar: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      // selectRoles:[],
      textMap: {
        update: '编辑',
        create: '创建',
        accredit: '绑定角色'
      },
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { validator: validateUserName, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        newPassword2: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
        /* selectRoles: [
          { required: true, message: '角色不能为空', trigger: 'change' }
        ] */
      },
      downloadLoading: false,
      loading: false
    }
  },
  computed: {
    headers () {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      listAdmin(this.listQuery).then(response => {
        console.log("response.data.code",response.data.code)
        if(response.data.code==200){
          this.list = response.data.data.records
          this.total = response.data.data.total
          this.listLoading = false
        }
      }).finally(() => this.listLoading = false)
    },
    getRelation (accountId) {
      let selectRoles = []
      relation(accountId).then(response => {
        if(response.data.code==200){
          let data = response.data.data
          this.roleOptions = response.data.data
          data.forEach(v => {
            if (v.checked) {
              selectRoles.push(v.roleId)
            }
          })
          this.dataForm.selectRoles = selectRoles
        // this.dialogFormVisible = true
        }
      })
    },
    changePagination ({ page, limit }) {
      // console.log('changePagination', page, limit)
      if (page) this.listQuery.current = page
      if (limit) this.listQuery.size = limit
      this.getList()
    },
    handleFilter () {
      this.listQuery.current = 1
      this.getList()
    },
    resetForm () {
      this.dataForm = {
        id: undefined,
        username: undefined,
        password: undefined,
        newPassword2: undefined,
        name: undefined,
        avatar: undefined
      }
    },
    uploadAvatar: function (response) {
      this.dataForm.avatar = response.data.url
    },
    handleCreate () {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData () {
      this.$refs['dataForm'].validate(valid => {
        if (valid && !this.loading) {
          this.loading = true
          let data = JSON.parse(JSON.stringify(this.dataForm))
          data.password = md5(data.password)
          createAdmin(data)
            .then(response => {
              if(response.data.code==200){
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加账号成功',
                  duration: 3000
                })
                this.getList()
              }
            })
            .finally(() => this.loading = false)
          // .catch(response => {
          //   this.$notify.error({
          //     title: '失败',
          //     message: response.data.errmsg
          //   })
          // })
        }
      })
    },
    handleUpdate (row, type) {
      row.name = row.accountName
      row.selectRoles = []
      this.dataForm = Object.assign({}, row)

      // this.dataForm.name=this.dataForm.accountName
      if (type) {
        //绑定角色
        this.dialogStatus = 'accredit'
        this.getRelation(row.accountId)
        // roleOptions()
        // .then(response => {
        //   this.roleOptions=response.data.data
        //   this.getRelation(row.accountId)
        // })
      } else {
        this.dialogStatus = 'update'
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      this.$refs['dataForm'].validate(valid => {
        if (valid && !this.loading) {
          this.loading = true
          if (this.dialogStatus == 'update') {
            let data = {
              id: this.dataForm.accountId,
              name: this.dataForm.name
            }
            updateAdmin(data)
              .then((response) => {
                if(response.data.code==200){
                  this.getList()
                  this.dialogFormVisible = false
                  this.$notify.success({
                    title: '成功',
                    message: '更新账号成功',
                    duration: 3000
                  })
                }
              })
              .finally(() => this.loading = false)
          } else {
            //绑定角色
            let data = {
              accountId: this.dataForm.accountId,
              roleIds: this.dataForm.selectRoles
            }
            bindRole(data)
              .then((response) => {
                if(response.data.code==200){
                  this.getList()
                  this.dialogFormVisible = false
                  this.$notify.success({
                    title: '成功',
                    message: '绑定角色成功',
                    duration: 3000
                  })
                }
              })
              .finally(() => this.loading = false)
          }
        }
      })
    },
    handleDelete (row) {
      this.$confirm('确定删除这个账号吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAdmin(row).then(response => {
            if(response.data.code==200){
              this.$notify.success({
                title: '成功',
                message: '删除账号成功',
                duration: 3000
              })
              if (
                this.total > this.listQuery.size &&
                this.total % this.listQuery.size === 1
              ) {
                this.listQuery.current -= 1
              }
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
    // handleDownload () {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['ID', '账号', '头像']
    //     const filterVal = ['id', 'username', 'avatar']
    //     excel.export_json_to_excel2(tHeader, this.list, filterVal, '信息')
    //     this.downloadLoading = false
    //   })
    // }
  }
}
</script>
